package com.mybatis.session.defaults;

import com.mybatis.cfg.Configuration;
import com.mybatis.proxy.MapperProxy;
import com.mybatis.session.SqlSession;
import com.mybatis.utils.DataSourceUtils;

import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * SqlSession接口的实现类
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Connection connection;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        connection = DataSourceUtils.getConnection(configuration);
    }

    /**
     * 用于创建代理对象
     * @param var1
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<T> var1) {
        return (T) Proxy.newProxyInstance(var1.getClassLoader(), new Class[]{var1}, new MapperProxy(configuration.getMappers(), connection));
    }

    /**
     * 用于释放资源
     */
    @Override
    public void close() {
        if(connection != null){
            try {
                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
